package com.example.my.android;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.tabs.TabLayout;

import java.sql.Struct;
import java.util.Base64;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class HomeActivity extends AppCompatActivity {

    private boolean isBackPressed = false;
    private Timer timer = null;
    private ListView studentList;
    private List<Map<String, Object>> students;//数据源
    private List<Student> students1;//数据源

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        studentList = findViewById(R.id.student_list);
        studentList.setOnCreateContextMenuListener(this);
//        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
//                android.R.layout.simple_list_item_1, students);
//        studentList.setAdapter(adapter);

//        initData();
        initData2();
        loadDataFromDatabase();
    }

    private void loadDataFromDatabase() {
        students1.clear();

        MyDb myDb = new MyDb(this);
        SQLiteDatabase db = myDb.getReadableDatabase();
        Cursor cursor = db.query("students", new String[]{"code", "name", "age", "gender"},
                null, null, null, null, "name");
        while(cursor.moveToNext()){
            Student student = new Student();
            student.setNo(cursor.getString(cursor.getColumnIndex("code")));
            student.setName(cursor.getString(cursor.getColumnIndex("name")));
            student.setAge(cursor.getInt(cursor.getColumnIndex("age")));
            student.setGender(cursor.getString(cursor.getColumnIndex("gender")));

            students1.add(student);
        }
    }

    private void initData2() {
        students1 = new LinkedList<>();

//        Student student = new Student();
//        student.setNo("201901060101");
//        student.setName("张三");
//        student.setAge(19);
//        student.setGender("男");
//        students1.add(student);
//
//        student = new Student();
//        student.setNo("201901060102");
//        student.setName("李四");
//        student.setAge(20);
//        student.setGender("女");
//        students1.add(student);
//
//        student = new Student();
//        student.setNo("201901060103");
//        student.setName("王五");
//        student.setAge(21);
//        student.setGender("男");
//        students1.add(student);
//
//        student = new Student();
//        student.setNo("201901060104");
//        student.setName("赵六");
//        student.setAge(22);
//        student.setGender("女");
//        students1.add(student);

        BaseAdapter adapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return students1.size();
            }

            @Override
            public Object getItem(int position) {
                return students1.get(position);
            }

            @Override
            public long getItemId(int position) {
//                Object item = getItem(position);
//                return item.hashCode();

                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                Object item = getItem(position);
                Student student = (Student) item;

                if(convertView==null) {
                    convertView = getLayoutInflater().inflate(R.layout.item_student, null);
                }
                TextView textView = convertView.findViewById(R.id.no_text);
                textView.setText(student.getNo());
                textView = convertView.findViewById(R.id.name_text);
                textView.setText(student.getName());
                textView = convertView.findViewById(R.id.age_text);
                textView.setText(String.valueOf(student.getAge()));

                ImageView photoImage = convertView.findViewById(R.id.photo_image);
                if("男".equals(student.getGender())){
                    photoImage.setImageResource(R.drawable.ic_boy);
                }else if("女".equals(student.getGender())){
                    photoImage.setImageResource(R.drawable.ic_girl);
                }

                return convertView;
            }
        };
        studentList.setAdapter(adapter);
    }

    private void initData() {
        students = new LinkedList<>();
        Map<String, Object> student = new HashMap<>();
        student.put("no", "201901060101");
        student.put("name", "张三");
        student.put("age", 19);
        students.add(student);

        student = new HashMap<>();
        student.put("no", "201901060102");
        student.put("name", "李四");
        student.put("age", 20);
        students.add(student);

        student = new HashMap<>();
        student.put("no", "201901060103");
        student.put("name", "王五");
        student.put("age", 18);
        students.add(student);

        student = new HashMap<>();
        student.put("no", "201901060104");
        student.put("name", "赵六");
        student.put("age", 23);
        students.add(student);

        SimpleAdapter adapter = new SimpleAdapter(this,
                students, R.layout.item_student,
                new String[]{"no", "name", "age"},
                new int[]{R.id.no_text, R.id.name_text, R.id.age_text});
        studentList.setAdapter(adapter);
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();

        if (isBackPressed == true) {
            if (timer != null) {
                timer.cancel();
                timer.purge();
                timer = null;
            }

            finish();
        }

        isBackPressed = true;
        Toast.makeText(getApplicationContext(), "再按一次推出程序。", Toast.LENGTH_LONG).show();

        //TODO:两秒之后，将isBackPressed设置为false即可
        if (timer == null) {
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    isBackPressed = false;
                    Log.d("TEST", "执行了计划任务。");

                    timer.cancel();
                    timer.purge();
                    timer = null;
                }
            }, 2000);
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu,
                                    View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        getMenuInflater().inflate(R.menu.menu_home_student, menu);
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        if(item.getItemId()==R.id.delete_student_menu){
            new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("是否删除当前选中的记录？")
                    .setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            AdapterView.AdapterContextMenuInfo acmi =
                                    (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
                            int position = acmi.position;
                            Student student = students1.get(position);
                            String code = student.getNo();

                            //删除学生的信息
                            MyDb myDb = new MyDb(getApplicationContext());
                            SQLiteDatabase db = myDb.getWritableDatabase();
                            int rows = db.delete("students", "code = ?",
                                    new String[]{code});
                            if (rows > 0) {
                                Toast.makeText(getApplicationContext(),
                                        "成功删除指定学生记录",
                                        Toast.LENGTH_LONG).show();
                                loadDataFromDatabase();
                            } else {
                                Toast.makeText(getApplicationContext(),
                                        "删除指定学生记录时发生错误",
                                        Toast.LENGTH_LONG).show();
                            }
                        }
                    })
                    .setNegativeButton("否", null)
                    .show();
        }
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        menu.add(0, 1, 1, "新增");
        getMenuInflater().inflate(R.menu.menu_home, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if(item.getItemId()==R.id.menu_add_student){
            Intent intent = new Intent(this, StudentInfoActivity.class);
            startActivityForResult(intent, 1);
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode,
                                    int resultCode,
                                    @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode==1){
            if(resultCode==RESULT_OK){
                boolean success = data.getBooleanExtra("success", false);
                if(success){
                    Toast.makeText(this, "新增用户信息成功", Toast.LENGTH_LONG).show();
                    loadDataFromDatabase();
                }else{
                    Toast.makeText(this, "新增用户信息失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}